package com.curso.lab1.dao.impl;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.hibernate.Query;
import org.hibernate.Session;

import com.curso.lab1.dao.intf.CredentialDAO;
import com.curso.lab1.model.Credential;

public class CredentialDAOImpl implements CredentialDAO {

	private Session session;
	
	public CredentialDAOImpl(Session session) {
		this.session = session;
	}
	
	@SuppressWarnings("unchecked")
	public List<Credential> getAll() {
		Query query = session.createQuery("from Credential");
		return query.list();
	}

	public Credential get(Long id) {
		return (Credential)session.get(Credential.class, id);
	}

	public boolean exists(Long id) {
		Credential cred = get(id);
		return cred != null;
	}

	public Credential save(Credential credential) {
		session.save(credential);
		return credential;
	}

	public void delete(Long id) {
		Query query = session.createSQLQuery("delete from credentials where id = :id");
		query.setParameter("id", id);
		query.executeUpdate();
	}

	public List<Credential> findByNamedQuery(String queryName, Map<String, Object> queryParams) {
		Query query = session.getNamedQuery(queryName);
		if (queryParams != null) {
			for (Entry<String, Object> element : queryParams.entrySet()) {
				query.setParameter(element.getKey(), element.getValue());
			}
		}
        return query.list();
	}

	public Credential getCredentialByUsername(String username) {
		Query query = session.createQuery("from Credential where username = :username");
		query.setParameter("username", username);
		query.setMaxResults(1);
		Credential cred = null;
		@SuppressWarnings("unchecked")
		List<Credential> credentials = query.list(); 
		if (!credentials.isEmpty())
			cred = credentials.get(0);
		return cred;
	}

}
